package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword 关键字
     * @param userId  当前登录的用户
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1. 根据关键词查询mongodb中是否有该关键词的记录
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch search = mongoTemplate.findOne(query, ApUserSearch.class);

        //2. 如果有记录就更新创建时间
        if (null != search) {
            search.setCreatedTime(new Date());
            mongoTemplate.save(search);
            return;
        }

        //3. 如果没有记录则查询当前登录用户的所有的搜索记录
        query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);

        //4. 判断是否 <10条 如果小于则直接插入数据 如果大于等于则更新替换最老的一行记录
        search = new ApUserSearch();
        search.setCreatedTime(new Date());
        search.setKeyword(keyword);
        search.setUserId(userId);

        if (null != list && list.size() < 10) {
            mongoTemplate.save(search);
        } else {
            ApUserSearch last = list.get(list.size() - 1);

            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(last.getId())), search);
        }
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {

        ApUser apUser = AppThreadLocalUtil.get();
        List<ApUserSearch> list = new ArrayList<>(0);

        if (null != apUser) {
            Query query = Query.query(Criteria.where("userId").is(apUser.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime"));
            list = mongoTemplate.find(query, ApUserSearch.class);
        }

        return ResponseResult.okResult(list);
    }

    /**
     * 删除搜索历史
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if (null == historySearchDto || StringUtils.isNotEmpty(historySearchDto.getId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtil.get();

        if (null == apUser) {
            ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.remove(Query.query(Criteria.where("id")
                        .is(historySearchDto.getId())
                        .and("userId")
                        .is(apUser.getId())),
                ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
